import { FFmpegTask } from './base'

/**
 * 音视频分离选项
 */
export interface SeparateOptions {
  input: string
  extractType: 'audio' | 'video' | 'both'
  audioOutput?: string // 音频输出路径
  videoOutput?: string // 视频输出路径
  audioFormat?: string // 音频格式 mp3, aac, wav等
  audioCodec?: string // 音频编码
  audioBitrate?: string // 音频码率
}

/**
 * 提取音频
 */
export function extractAudio(options: {
  input: string
  output: string
  format?: string
  bitrate?: string
}): FFmpegTask {
  const args: string[] = ['-i', options.input, '-y', '-vn'] // -vn 去除视频流

  // 音频编码
  if (options.format) {
    const codecMap: Record<string, string> = {
      mp3: 'libmp3lame',
      aac: 'aac',
      wav: 'pcm_s16le',
      flac: 'flac',
      m4a: 'aac'
    }
    const codec = codecMap[options.format]
    if (codec) {
      args.push('-c:a', codec)
    }
  } else {
    args.push('-c:a', 'copy') // 直接复制音频流
  }

  if (options.bitrate) {
    args.push('-b:a', options.bitrate)
  }

  args.push(options.output)

  return new FFmpegTask(args, options.input)
}

/**
 * 提取视频（无音频）
 */
export function extractVideo(options: {
  input: string
  output: string
  codec?: string
}): FFmpegTask {
  const args: string[] = [
    '-i',
    options.input,
    '-y',
    '-an' // -an 去除音频流
  ]

  if (options.codec) {
    args.push('-c:v', options.codec)
  } else {
    args.push('-c:v', 'copy') // 直接复制视频流
  }

  args.push(options.output)

  return new FFmpegTask(args, options.input)
}

/**
 * 音视频分离（同时提取）
 */
export function separateAudioVideo(options: SeparateOptions): Promise<void> {
  const tasks: Promise<void>[] = []

  if (options.extractType === 'audio' || options.extractType === 'both') {
    if (!options.audioOutput) {
      throw new Error('audioOutput is required when extracting audio')
    }
    const audioTask = extractAudio({
      input: options.input,
      output: options.audioOutput,
      format: options.audioFormat,
      bitrate: options.audioBitrate
    })
    tasks.push(audioTask.start())
  }

  if (options.extractType === 'video' || options.extractType === 'both') {
    if (!options.videoOutput) {
      throw new Error('videoOutput is required when extracting video')
    }
    const videoTask = extractVideo({
      input: options.input,
      output: options.videoOutput
    })
    tasks.push(videoTask.start())
  }

  return Promise.all(tasks).then(() => {})
}
